package com.sea.supply.controller;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.operate.entity.RelatedMaterial;
import com.sea.operate.entity.RelatedMaterialDetail;
import com.sea.operate.entity.RelatedSku;
import com.sea.physical.entity.CreateDistributeSku;
import com.sea.supply.entity.PdfFile;
import com.sea.supply.entity.PdfRead;
import com.sea.supply.entity.Produce;
import com.sea.supply.service.PdfFileService;
import com.sea.supply.service.PdfService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 *  设计部控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/pdfSku")
public class PdfSkuController {
    @Autowired
    private PdfService pdfService;
    @Autowired
    private PdfFileService pdfFileService;

    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/supply/pdfSku/main";
    }

    @RequestMapping("/record")
    public String main(Model model, @RequestParam("createPlanNo") String createPlanNo) {
        model.addAttribute("createPlanNo", createPlanNo);
        return "/sea/supply/pdfSku/record";
    }

    @RequestMapping("/back")
    public String back(Model model) {
        return "/sea/supply/pdfSku/back";
    }

    @RequestMapping("/editPage")
    public String editPage(Model model, @RequestParam("ids") String ids) {
        model.addAttribute("ids", ids);
        return "/sea/supply/pdfSku/edit";
    }

    @ResponseBody
    @RequestMapping("/findByPdfPlanNo")
    public AjaxTableReturn findByPdfPlanNo(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                           @RequestParam(value = "offset", defaultValue = "0") int start,
                                           PdfFile pdfFile) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<PdfRead> list = pdfService.findByPdfPlanNo(pdfFile);
        PageInfo<PdfRead> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     PdfFile pdfFile) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<PdfFile> list = pdfFileService.findByCnd(pdfFile);
        PageInfo<PdfFile> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @RequestMapping("/importPdfSku")
    @ResponseBody
    public AjaxReturn importPdfSku(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {

                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".pdf"))) {
                    return result.setMsg("只能上传pdf文件！！！");
                }
                pdfService.importPdfBySku(file, fileName);
//                productService.importSku(file.getInputStream(), fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/downloadPdf")
    public AjaxReturn export(HttpServletResponse response, @RequestParam("ids") Integer ids[]) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try {
            List<PdfFile> list = pdfFileService.getRows(ids);

            List<String> fileUrls = new ArrayList<>();
            for (PdfFile pdfFile:list){
                if(StringUtils.isNotBlank(pdfFile.getPdfFile())){
                    fileUrls.add(pdfFile.getPdfFile());
                }
            }
            // 下载链接列表

            if(fileUrls.size()==0){
                return result.setMsg("暂无获取到SKU信息");
            }
            ByteArrayInputStream zipInputStream = createZipStreamFromUrls(fileUrls);
            System.out.println("ZIP 文件流已生成，可用于进一步处理！");
            // 例如将流写入文件或传递给 HTTP 响应
            OSSClient ossClient=new OSSClient("http://oss-cn-beijing.aliyuncs.com",
                    "LTAI4G55LJEk8nARtrjYngou",
                    "XPbdMs0xrRGAsmKVm9VYC8bSTTuFhl");
            InputStream inputStream = zipInputStream;
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("application/octet-stream");
            String filename = "合并SKU.zip";
            //获取文件后缀名
            String prefix=filename.substring(filename.lastIndexOf(".")+1);
            // //修改后的文件名
            String fileUUIDname = UUID.randomUUID().toString();
            //修改后的文件名(带后缀)
            String NewFileName = fileUUIDname + "." + prefix;
            ossClient.putObject("cozylux", filename, inputStream,metadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 50);
            String url = ossClient.generatePresignedUrl("cozylux", filename, expiration).toString();
            result.setOk(true).setMsg(url);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    public static ByteArrayInputStream createZipStreamFromUrls(List<String> fileUrls) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try (ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream)) {
            for (String fileUrl : fileUrls) {
                addUrlFileToZip(fileUrl, zipOut);
            }
        }

        // 将 ByteArrayOutputStream 转为 ByteArrayInputStream 供调用方读取
        return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }

    private static void addUrlFileToZip(String fileUrl, ZipOutputStream zipOut) {
        try (InputStream in = new URL(fileUrl).openStream()) {
            String fileName = Paths.get(new URL(fileUrl).getPath()).getFileName().toString();
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOut.putNextEntry(zipEntry);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                zipOut.write(buffer, 0, len);
            }
            zipOut.closeEntry();
            System.out.println("已添加文件到压缩包：" + fileName);

        } catch (IOException e) {
            System.err.println("下载失败：" + fileUrl);
            e.printStackTrace();
        }
    }
}



